<?php
namespace Api\Controller;

class GroupController extends APIController {
    public $tbName = CONTROLLER_NAME;

    /*待验证的参数*/
    public $tca = [
        'user_id' => [
            'method' => 'exists',
            'model' => 'member',
            'code_key' => 'lawless'
        ],
    ];
    /**
     * 列表页面
     */
    public function index() {
        try{
            $this->safeChecked();
            $page = I('param.page',C('PAGE'));
            $show_num = I('param.show_num',C('SHOW_NUM'));
            $Obj = D($this->tbName); //实例化对象
            $type = I('param.type',1);
            $where = [
                'deleted' => 0,
                'hidden' => 0,
                'type' => $type,
            ];
            $list = $Obj
                    ->where($where)
                    ->Field('id.name')
                    ->order('crdate desc')
                    ->limit(($page -1)*$show_num,$show_num)
                    ->select();
            $this->res_data['data'] = $list?:array();
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 用户拼团
     */
    public function list() {
        try{
            $this->safeChecked();
            /*验证*/
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $page = I('param.page',C('PAGE'));
            $show_num = I('param.show_num',C('SHOW_NUM'));
            $Obj = D($this->tbName); //实例化对象
            //查询条件 $type 等于0表示用户发起的团 等于1表示参与的团
            $type = I('param.type',0);
            $user_id = I('param.user_id');
            $where = [];
            if($type == 0){
                $where['a.user_id'] = $user_id;
                $where['a.type'] = ['IN',[1,2]];
                $list = $Obj
                    ->alias('a')
                    ->join(C('DB_PREFIX').'activity as b ON a.activity_id = b.id')
                    ->join(C('DB_PREFIX').'goods as c ON b.goods_id = c.id')
                    ->where($where)
                    ->Field('a.id,a.crdate as createtime,a.type,a.complete_time,a.expired,b.id as activity_id,c.id as goods_id,c.name,c.image,c.crdate,c.remark')
                    ->order('a.crdate desc')
                    ->limit(($page -1)*$show_num,$show_num)
                    ->select();
            }else{
                $where = [
                    'a.user_id' => ['neq',$user_id],
                    'b.user_id' => $user_id
                ];
                $list = $Obj
                    ->alias('a')
                    ->join(C('DB_PREFIX').'order as b ON b.group_id = a.id')
                    ->join(C('DB_PREFIX').'activity as c ON a.activity_id = c.id')
                    ->join(C('DB_PREFIX').'goods as d ON c.goods_id = d.id')
                    ->where($where)
                    ->Field('a.id,a.crdate as createtime,a.type,a.complete_time,a.expired,c.id as activity_id,d.id as goods_id,d.name,d.image,d.crdate,d.remark')
                    ->order('a.crdate desc')
                    ->limit(($page -1)*$show_num,$show_num)
                    ->select();
            }
            if($list){
                $Plan = M('plan');
                $GoodsInfo = M('goods_info');
                foreach ($list as $key => &$value) {
                    $value['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$value['crdate']).'/'.$value['image'];
                    $plans = $Plan->where(array('activity_id' => $value['activity_id'],'deleted' => 0))->Field('group_price')->order('group_price asc')->select();
                    $value['price'] = $plans[0]['group_price'];
                    $goods_info = $GoodsInfo->where(array('goods_id' => $value['goods_id'],'deleted' => 0))->Field('sale_price')->order('sale_price asc')->select();
                    $value['sale_price'] = $goods_info[0]['sale_price'];
                    $value['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
                    $value['remark'] = explode(',', $value['remark']);
                    if($value['complete_time'] > 0){
                        $value['status'] = '拼团成功';
                    }else{
                        if($value['expired'] > time()){
                            $value['status'] = '待成团';
                        }else{
                            $value['status'] = '拼团失败';
                        }
                    }
                }
            }
            $this->res_data['data'] = $list?:array();
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 拼团详情
     */
    public function info() {
        try{
            static $data = [];
            $this->safeChecked();
            /*验证*/
            $check = D('Validate','Util');
            $this->tca = [
                'group_id' => [
                    'method' => 'exists',
                    'model' => 'group',
                    'code_key' => 'lawless'
                ],
            ];
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $group_id = I('param.group_id');
            $Obj = D($this->tbName); //实例化对象
            $where['a.id'] = $group_id;
            $list = $Obj
                ->alias('a')
                ->join(C('DB_PREFIX').'activity as b ON a.activity_id = b.id')
                ->join(C('DB_PREFIX').'goods as c ON b.goods_id = c.id')
                ->where($where)
                ->Field('a.id,a.type,a.crdate as createtime,a.complete_time,a.expired,a.user_id,b.id as activity_id,b.num,c.id as goods_id,c.name,c.image,c.crdate,c.remark')
                ->select();
            $list = current($list);
            $Plan = M('plan');
            $GoodsInfo = M('goods_info');
            $list['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$list['crdate']).'/'.$list['image'];
            $plans = $Plan->where(array('activity_id' => $list['activity_id'],'deleted' => 0))->Field('group_price')->order('group_price asc')->select();
            $list['price'] = $plans[0]['group_price'];
            $goods_info = $GoodsInfo->where(array('goods_id' => $list['goods_id'],'deleted' => 0))->Field('sale_price')->order('sale_price asc')->select();
            $list['sale_price'] = $goods_info[0]['sale_price'];
            $list['createtime'] = date('Y-m-d H:i:s',$list['createtime']);
            $list['remark'] = explode(',', $list['remark']);
            //团状态 0进行中 1拼团成功 2拼团失败
            if($list['complete_time'] > 0){
                $list['status'] = 1;
            }else{
                if($list['expired'] > time()){
                    $list['status'] = 0;
                }else{
                    $list['status'] = 2;
                }
            }
            $list['expired'] = date('Y-m-d H:i:s',$list['expired']);
            //参团人员
            $Order = M('order');
            $list['member'] = $Order
                            ->alias('a')
                            ->join(C('DB_PREFIX').'member as b ON a.user_id = b.id')
                            ->where(['a.group_id' => $list['id']])
                            ->Field('b.wxlogo,b.nickname,a.user_id')
                            ->order('a.id asc')
                            ->select()?:[];
            $data['info'] = $list;
            //商品价格方案
            $price_plans = $Plan
                        ->alias('a')
                        ->join(C('DB_PREFIX').'goods_info as b ON a.goods_info_id = b.id')
                        ->where(array('a.deleted' => 0,'a.activity_id' => $list['activity_id']))
                        ->Field('a.goods_info_id,a.group_price,a.leader_price,b.assistant,b.stock,b.sale_price')
                        ->order('a.group_price ASC')
                        ->select();
            $data['plans'] = $price_plans;
            //活动详细
            $data['activity'] = M('activity')->find($list['activity_id']);
            //商品
            $Goods = M('goods');
            $goods = $Goods->Field('id,name,remark,image,crdate,content,links,postage_price')->find($list['goods_id']);
            $goods['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$goods['crdate']).'/'.$goods['image'];
            $goods['sales'] = M('order')->where(array('goods_id' => $goods['id']))->sum('num')?:0;
            $data['goods'] = $goods;
            //当前活动的其他团 默认显示前两个
            $other_groups = $Obj
                            ->alias('a')
                            ->join(C('DB_PREFIX').'member as b ON a.user_id = b.id')
                            ->where(['a.activity_id' => $list['activity_id'],'a.id' => ['neq',$group_id],'a.complete_time' =>0,'a.expired' => ['gt',time()],'a.state' => 1])
                            ->Field('a.id,a.expired,b.wxlogo,b.nickname')
                            ->limit(0,2)
                            ->order('a.crdate desc')
                            ->select()?:[];
            if($other_groups){
                foreach ($other_groups as $key => &$value) {
                    $value['expired'] = date('Y-m-d H:i:s',$value['expired']);
                }
            }
            $data['other'] = $other_groups;
            //更多拼团 默认显示4个
            $Activity = M('activity');
            $activities = $Activity
                    ->where(array('type' => 1,'deleted' => 0,'hidden' => 0,'start' => array('lt',time()),'end' => array('gt',time())))
                    ->Field('goods_id,id,num')
                    ->limit(0,4)
                    ->order('crdate desc')
                    ->select();
            if($activities){
                $Goods = M('goods');
                foreach($activities as $key => &$val){
                    //获取最低拼团价
                    $activity_price = $Plan->where(array('activity_id' => $val['id'],'deleted' => 0))->Field('group_price')->order('group_price asc')->limit(0,1)->select();
                    $val['price'] = $activity_price[0]['group_price'];
                    $price[] = $val['price'];
                    $goods = $Goods->Field('crdate,image,name,remark')->find($val['goods_id']);
                    $val['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$goods['crdate']).'/'.$goods['image'];
                    $val['name'] = $goods['name'];
                    $val['remark'] = explode(',', $val['remark']);
                    //获取该活动下的所有开团数量
                    $groups = $Obj->where(array('activity_id' => $val['id']))->Field('id')->select();
                    $group_ids = [];
                    if($groups){
                        $group_ids = array_map(function($val){
                            return $group_ids[] = $val['id'];
                        },$groups);
                    }
                    $val['sales'] = 0;
                    if($group_ids){
                        $val['sales'] = $Order->where(array('group_id' => array('IN',$group_ids)))->count()?:0;
                    }
                    $sales[] = $val['sales'];
                }
            }              
            $data['more'] = $activities;                   
            $this->res_data['data'] = $data;
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 超级团长-建团列表
     */
    public function colonelList() {
        try{
            $this->safeChecked();
            /*验证*/
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $page = I('param.page',C('PAGE'));
            $show_num = I('param.show_num',C('SHOW_NUM'));
            $Obj = D('Activity'); //实例化对象
            //查询条件 status 等于0全部 等于1进行中  2已完成
            $status = I('param.status',0);
            $user_id = I('param.user_id');
            $where['a.user_id'] = $user_id;
            $where['a.deleted'] = 0;
            switch($status){
                case 1:
                    $where['a.start'] = ['lt',time()];
                    $where['a.end'] = ['gt',time()];
                    $where['b.complete_time'] = 0;
                    break;
                case 2:
                    $where['b.complete_time'] = ['gt',0];
                    break;
            }
            $list = $Obj
                    ->alias('a')
                    ->join(C('DB_PREFIX').'group as b ON b.activity_id = a.id')
                    ->join(C('DB_PREFIX').'goods as c ON a.goods_id = c.id')
                    ->join(C('DB_PREFIX').'member as d ON a.user_id = d.id')
                    ->where($where)
                    ->Field('a.id as activity_id,a.hidden,b.id,b.num,b.group_num,b.complete_time,b.expired,c.id as goods_id,c.name,c.image,c.crdate,d.wxlogo')
                    ->order('a.crdate desc')
                    ->limit(($page -1)*$show_num,$show_num)
                    ->select();
            if($list){
                $Order = M('order');
                $Plan = M('plan');
                $GoodsInfo = M('goods_info');
                foreach ($list as $key => &$value) {
                    $value['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$value['crdate']).'/'.$value['image'];
                    $plans = $Plan->where(array('activity_id' => $value['activity_id'],'deleted' => 0))->Field('group_price')->order('group_price asc')->select();
                    $value['price'] = $plans[0]['group_price'];
                    $goods_info = $GoodsInfo->where(array('goods_id' => $value['goods_id'],'deleted' => 0))->Field('sale_price')->order('sale_price asc')->select();
                    if($value['hidden']){
                        $value['status'] = '已取消';
                    }else{
                        if($value['complete_time'] > 0){
                            $value['status'] = '已完成';
                        }else{
                            if($value['expired'] > time()){
                                $value['status'] = '进行中';
                            }else{
                                $value['status'] = '拼团失败';
                            }
                        }
                    }
                    $value['expired'] = date('Y-m-d H:i:s',$value['expired']);
                    //获取团成员
                    $member = $Order
                            ->alias('a')
                            ->join(C('DB_PREFIX').'member as b ON a.user_id = b.id')
                            ->where(array('a.group_id' => $value['id']))
                            ->Field('b.wxlogo')
                            ->select();
                    //$value['member'][] = $value['wxlogo'];
                    $value['member'] = [];
                    if($member){
                        $value['member'] = array_map(function($val){
                            return $value['member'][] = $val['wxlogo'];
                        },$member);
                    }

                    //计算该团生成的预估佣金
                    $orders = $Order->where(array('is_pay' => 1,'group_id' => $value['id']))->Field('deal_money,distribution_money,num')->select();
                    $value['comission'] = 0;
                    if($orders){
                        foreach($order as $val){
                            $value['comission'] += ($val['deal_money'] - $val['distribution_money'])*$val['num'];
                        }
                    }
                }
            }
            $this->res_data['data'] = $list?:array();
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 超级团长拼团详情
     */
    public function colonelInfo() {
        try{
            static $data = [];
            $this->safeChecked();
            /*验证*/
            $check = D('Validate','Util');
            $this->tca = [
                'group_id' => [
                    'method' => 'exists',
                    'model' => 'group',
                    'code_key' => 'lawless'
                ],
            ];
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $group_id = I('param.group_id');
            $Obj = D($this->tbName); //实例化对象
            $where['a.id'] = $group_id;
            $list = $Obj
                ->alias('a')
                ->join(C('DB_PREFIX').'activity as b ON a.activity_id = b.id')
                ->join(C('DB_PREFIX').'goods as c ON b.goods_id = c.id')
                ->join(C('DB_PREFIX').'member as d ON a.user_id = d.id')
                ->where($where)
                ->Field('a.id,a.type,a.crdate as createtime,a.complete_time,a.expired,a.user_id,a.activity_id,b.is_support_coupon,b.num,c.id as goods_id,c.name,c.image,c.crdate,c.remark,c.postage_price,d.id as user_id,d.wxlogo,d.nickname')
                ->select();
            $list = current($list);
            $Plan = M('plan');
            $GoodsInfo = M('goods_info');
            $list['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$list['crdate']).'/'.$list['image'];
            $plans = $Plan->where(array('activity_id' => $list['activity_id'],'deleted' => 0))->Field('group_price')->order('group_price asc')->select();
            $list['price'] = $plans[0]['group_price'];
            $goods_info = $GoodsInfo->where(array('goods_id' => $list['goods_id'],'deleted' => 0))->Field('sale_price')->order('sale_price asc')->select();
            $list['sale_price'] = $goods_info[0]['sale_price'];
            $list['createtime'] = date('Y-m-d H:i:s',$list['createtime']);
            $list['remark'] = explode(',', $list['remark']);
            //团状态 0进行中 1拼团成功 2拼团失败
            if($list['complete_time'] > 0){
                $list['status'] = 1;
            }else{
                if($list['expired'] > time()){
                    $list['status'] = 0;
                }else{
                    $list['status'] = 2;
                }
            }
            $list['expired'] = date('Y-m-d H:i:s',$list['expired']);
            //参团人员
            $Order = M('order');
            $list['member'] = $Order
                            ->alias('a')
                            ->join(C('DB_PREFIX').'member as b ON a.user_id = b.id')
                            ->where(['a.group_id' => $list['id']])
                            ->Field('a.deal_money,a.crdate,a.num,a.user_id,b.wxlogo,b.nickname')
                            ->order('a.id asc')
                            ->select()?:[];
            foreach ($list['member'] as $key => &$value) {
                $value['crdate'] = date('Y-m-d H:i:s',$value['crdate']);
            }
            $data['info'] = $list;
            //商品价格方案
            $price_plans = $Plan
                        ->alias('a')
                        ->join(C('DB_PREFIX').'goods_info as b ON a.goods_info_id = b.id')
                        ->where(array('a.deleted' => 0,'a.activity_id' => $list['activity_id']))
                        ->Field('a.goods_info_id,a.group_price,a.leader_price,b.assistant,b.stock,b.sale_price')
                        ->order('a.group_price ASC')
                        ->select();
            $data['plans'] = $price_plans;                  
            $this->res_data['data'] = $data;
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }
}

?>